<script setup>
import { ref, computed, onMounted } from 'vue'
import { useChatStore } from '@/stores/chatStore'
import { ElInput, ElAvatar, ElEmpty, ElButton, ElDialog, ElTag, ElMessageBox, ElMessage } from 'element-plus'
import request from '@/axios/utils/request'

const chatStore = useChatStore()
const search = ref('')

// 索引分组（与移动端一致）
const indexList = [
  '☆', ...Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i)), '#'
]

// 过滤后的分组好友
const filteredFriendListShow = computed(() => {
  if (!search.value.trim()) return chatStore.friendListShow
  // 按分组过滤
  return chatStore.friendListShow.map(group =>
    group.filter(friend => friend.name && friend.name.toLowerCase().includes(search.value.trim().toLowerCase()))
  )
})

// 总好友数
const totalFriends = computed(() =>
  chatStore.friendListShow.reduce((sum, group) => sum + group.length, 0)
)

// 弹窗与选中好友
const showFriendPop = ref(false)
const currentFriend = ref(null)
const selectUser = ref({})

// 点击更多按钮，弹窗并拉取资料
function handleMore(friend) {
  currentFriend.value = friend
  showFriendPop.value = true
  request.post('user/userInfoById', { uid: friend.id }).then(res => {
    selectUser.value = res.result || {}
  })
}

// 删除好友
function doDeleteFriend() {
  ElMessageBox.confirm('确定删除该好友吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.post('friend/deleteFriend', { id: currentFriend.value.id }).then(res => {
      if (res.code === 0) {
        ElMessage.success('操作成功')
        showFriendPop.value = false
        chatStore.getFriendList()
      }
    })
  })
}

// 发起聊天
async function gotoChat() {
  // 设置当前会话
  const session = chatStore.sessionList.find(s => s.chattingUserId === selectUser.value.uid)
  if (session) {
    chatStore.setChattingUserInfo(session)
    // 拉取历史消息
    await request.post('chat/list', {
      sessionId: session.sessionId,
      pageNum: 1,
      pageSize: 20
    }).then(res => {
      if (res.code === 0) {
        const data = res.data
        const pm = chatStore.personMessage.find(pm => pm.sessionId === data.sessionId)
        if (pm) {
          pm.lastMessageId = data.pageInfo.records.length ? data.pageInfo.records[0].id : 0
          pm.list = data.pageInfo.records.reverse()
          pm.pageNum = Number(data.pageInfo.current)
          pm.hasNextPage = pm.pageNum * Number(data.pageInfo.size) < Number(data.pageInfo.total)
        }
        showFriendPop.value = false
        window.$openChatPanel && window.$openChatPanel()
      } else {
        ElMessage.error('消息加载失败')
      }
    })
  }
}

// 查看资料（已在弹窗中展示）
function viewInfo() {
  // 可扩展为跳转资料页
}

// 进入聊天（点击头像/昵称）
function handleSelect(friend) {
  // 直接弹窗更多操作
  handleMore(friend)
}

onMounted(() => {
  if (!chatStore.friendList.length) {
    chatStore.getFriendList()
  }
})
</script>

<template>
  <div class="p-2 h-full flex flex-col">
    <ElInput v-model="search" placeholder="搜索好友昵称" clearable class="mb-2" />
    <div class="flex-1 overflow-y-auto">
      <template v-for="(group, idx) in filteredFriendListShow" :key="indexList[idx]">
        <div v-if="group.length" class="sticky top-0 z-10 bg-white font-bold px-2 py-1 border-b">{{ indexList[idx] }}</div>
        <div v-for="friend in group" :key="friend.id" class="flex items-center gap-3 px-2 py-2 cursor-pointer hover:bg-gray-100 rounded">
          <ElAvatar :src="friend.url" size="small" @click="handleSelect(friend)" />
          <span class="truncate flex-1" @click="handleSelect(friend)">{{ friend.name }}</span>
          <ElButton text icon="el-icon-more" @click.stop="handleMore(friend)" />
        </div>
      </template>
      <ElEmpty v-if="filteredFriendListShow.every(g => g.length === 0)" description="暂无好友信息" />
    </div>
    <div v-if="totalFriends > 0" class="text-center text-xs text-gray-400 mt-2">共{{ totalFriends }}位好友</div>

    <!-- 好友操作弹窗 -->
    <ElDialog v-model="showFriendPop" title="好友操作" width="350px" :close-on-click-modal="false">
      <div class="flex items-center gap-3 mb-2">
        <ElAvatar :src="selectUser.avatar" size="large" />
        <div>
          <div class="font-bold">{{ selectUser.nickname || selectUser.name }}</div>
          <div class="text-xs text-gray-400">ID: {{ selectUser.uid }}</div>
        </div>
      </div>
      <div class="mb-2">
        <ElTag v-if="selectUser.gender === 1" type="success">男</ElTag>
        <ElTag v-else-if="selectUser.gender === 2" type="danger">女</ElTag>
      </div>
      <div class="mb-2 text-xs text-gray-500">单位：{{ selectUser.unit || '-' }}</div>
      <div class="mb-2 text-xs text-gray-500">联系方式：{{ selectUser.phone || '-' }}</div>
      <div class="flex gap-2 mt-4">
        <ElButton type="primary" @click="gotoChat">发起聊天</ElButton>
        <ElButton type="info" @click="viewInfo">查看资料</ElButton>
        <ElButton type="danger" @click="doDeleteFriend">删除好友</ElButton>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped>
.sticky {
  position: sticky;
  top: 0;
  background: #fff;
}
</style> 